import React, { useEffect, useMemo, useState, useCallback, useRef } from 'react'
import { DnFC, registerDialogInstances } from '@designable/react'
import { Modal } from 'antd'
import { v4 as uuidv4 } from 'uuid'
import { useFieldSchema } from '@formily/react'
import createEvent, { useT } from '@designable/event-system'
import { SchemaApp } from '../SchemaApp'

export const Dialog: DnFC<React.ComponentProps<any>> = (props) => {
  const $t = useT()
  const [open, setOpen] = useState(false)
  const dialogFormRef = useRef<any>(null)
  const uuid = useMemo(() => uuidv4(), [])
  const {
    width,
    title,
    dialogName,
    confirm,
    cancel,
    destroyOnClose,
    // 底部设置
    showFooter,
    okText,
    cancelText,
    okType,
    okButtonProps,
    cancelButtonProps,
    // 新增：form 传递相关 props
    ...restProps
  } = props
  const [awakener, setAwakener] = useState<any>({})
  const fieldSchema = useFieldSchema()

  // 使用 useMemo 缓存 schema 对象
  const schema = useMemo(() => {
    if (!fieldSchema?.properties) return null
    return {
      type: 'void',
      properties: fieldSchema.properties,
    }
  }, [fieldSchema?.properties])

  const dialogProps = useMemo(
    () => ({
      open: (props) => {
        setAwakener(props)
        setOpen(true)
      },
      close: (props) => {
        setAwakener(props)
        setOpen(false)
      },
    }),
    []
  )

  useEffect(() => {
    registerDialogInstances(uuid, {
      label: dialogName,
      value: dialogName,
      id: uuid,
      ...dialogProps,
    })
  }, [dialogName])

  // 处理确认操作
  const handleConfirm = useCallback(async () => {
    try {
      // 评估确认表达式
      if (confirm) {
        await createEvent(confirm, {
          ...awakener,
          form: dialogFormRef.current, // 当前组件的表单实例
        })
      }
      setOpen(false)
    } catch (error) {}
  }, [confirm, awakener])

  // 处理取消操作
  const handleCancel = useCallback(async () => {
    try {
      // 评估取消表达式
      if (cancel) {
        await createEvent(cancel, {
          ...awakener,
          form: dialogFormRef.current, // 当前组件的表单实例
        })
      }
      setOpen(false)
    } catch (error) {}
  }, [cancel, awakener])

  const handleFormReady = (formInstance: any) => {
    dialogFormRef.current = formInstance
  }

  return (
    <Modal
      width={Number(width) || 600}
      title={$t(title)}
      open={open}
      onCancel={handleCancel}
      onOk={handleConfirm}
      // 布局设置
      // 行为设置
      destroyOnClose={destroyOnClose !== false}
      // 样式设置
      footer={showFooter === false ? null : undefined}
      okText={okText ? $t(okText) : undefined}
      cancelText={cancelText ? $t(cancelText) : undefined}
      okType={okType}
      okButtonProps={okButtonProps}
      cancelButtonProps={cancelButtonProps}
      modalRender={(modal) => {
        return (
          <div id="formily-dialog-container" {...restProps}>
            {modal}
          </div>
        )
      }}
      getContainer={() => {
        return document.getElementById('designable-page-wrap') || document.body
      }}
    >
      {schema ? (
        <SchemaApp
          pageSchema={{
            formProps: {
              onFormReady: handleFormReady,
            },
            schema: schema,
          }}
        />
      ) : (
        props.children
      )}
    </Modal>
  )
}
